package com.tensquare.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2021/6/23.
 */
@Component
public class WebFilter extends ZuulFilter {


    //过滤器类型,pre:可以在请求被路由之前调用,route ：在路由请求时候被调用,
    // post ：在route和error过滤器之后被调用,error ：处理请求时发生错误时被调用
    @Override
    public String filterType() {
        return "pre";
    }

    //过滤器顺序  优先级为0，数字越大，优先级越低
    @Override
    public int filterOrder() {
        return 0;
    }
    //是否开启过滤器   是否执行该过滤器，此处为true，说明需要过滤
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //过滤器的具体逻辑。
    @Override
    /**
     * 在过滤器中将请求头信息转发到各个微服务中
     */
    public Object run() throws ZuulException {
        System.out.println("前台zuul过滤器生效了*******");
        //获取上下文对象RequestContext
        RequestContext context = RequestContext.getCurrentContext();
        //获取request,response对象
        HttpServletRequest request = context.getRequest();
        String token = request.getHeader("Authorization");

        //将请求头发转到各个微服务
        if (StringUtils.isNotBlank(token)){
            context.addZuulRequestHeader("Authorization",token);
        }
        return null;
    }
}
